package com.example.culturapp;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Calendar;

import android.app.ActionBar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TaskStackBuilder;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.MediaScannerConnectionClient;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.TextView;

public class ComposeEventActivity extends ActionBarActivity{
	private TextView mDateDisplay;
	private TextView hora;
	private TextView lugar;
	private TextView desc;
	
	private Button mPickDate;
	private Button elegirFoto;
	
	private Button tomarFoto;
	private Bitmap bitmap;
	private ImageView iv;
	private int mYear;    
	private int mMonth;    
	private int mDay;
	static final int DATE_DIALOG_ID = 0;
	private String name = "";
	private static int TAKE_PICTURE = 1;
	private static int SELECT_PICTURE = 2;
	private int code=0;
	private Model model= Model.getInstance();
	// the callback received when the user "sets" the date in the dialog
	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear;
			mDay = dayOfMonth;
			updateDisplay();
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.composeevent);

		final ActionBar actionBar = getActionBar();
		actionBar.setIcon(R.drawable.ico);
		actionBar.setDisplayShowTitleEnabled(false);
		actionBar.setDisplayHomeAsUpEnabled(false);

		// capture our View elements
		mDateDisplay = (TextView) findViewById(R.id.fecha);
		mPickDate = (Button) findViewById(R.id.pickDate);
		// add a click listener to the button
		mPickDate.setOnClickListener(new View.OnClickListener(){
			public void onClick(View v) {
				showDialog(DATE_DIALOG_ID);
			}
		});
		// get the current date

		final Calendar c = Calendar.getInstance();
		if(savedInstanceState!=null){
		int aux=savedInstanceState.getInt("mYear", 0);
		//if(aux==0)
		//	mYear = c.get(Calendar.YEAR);
		//else
			mYear=aux;
		aux=savedInstanceState.getInt("mMonth", 0);
		//if(aux==0)
		//	mMonth = c.get(Calendar.MONTH);
		//else
			mMonth =aux;
		aux=savedInstanceState.getInt("mDay", 0);
		//if(aux==0)
		//	mDay = c.get(Calendar.DAY_OF_MONTH);
		//else
			mDay =aux;
			
			iv = (ImageView)findViewById(R.id.imagen);
			code = savedInstanceState.getInt("code", 0);
			name = savedInstanceState.getString("name");
	        bitmap = savedInstanceState.getParcelable("bitmap");
		}else{
			mYear = c.get(Calendar.YEAR);
			mMonth = c.get(Calendar.MONTH);
			mDay = c.get(Calendar.DAY_OF_MONTH);
			iv = (ImageView)findViewById(R.id.imagen);
		}
		// display the current date (this method is below)
		updateDisplay();

		elegirFoto = (Button) findViewById(R.id.botonElegirFoto);
		// add a click listener to the button
		elegirFoto.setOnClickListener(new View.OnClickListener(){
			public void onClick(View v) {
				Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
				code = SELECT_PICTURE;
				startActivityForResult(intent, code);
			}
		});

		tomarFoto = (Button) findViewById(R.id.botonTomarFoto);
		// add a click listener to the button
		tomarFoto.setOnClickListener(new View.OnClickListener(){
			public void onClick(View v) {
				name = Environment.getExternalStorageDirectory() + "/test.jpg";
				Uri output = Uri.fromFile(new File(name));
				Intent intent =  new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
				code = TAKE_PICTURE;
				intent.putExtra(MediaStore.EXTRA_OUTPUT, output);

				startActivityForResult(intent, code);
			}
		});
		hora = (TextView) findViewById(R.id.hora);
		lugar = (TextView) findViewById(R.id.lugar);
		desc = (TextView) findViewById(R.id.descripcion);
		
		Button crear = (Button) findViewById(R.id.botonCrear);
		
		crear.setOnClickListener(new View.OnClickListener(){
			public void onClick(View v) {
				ItemHoy item = new ItemHoy("F. Martinelli", bitmap , desc.getText()+"", mDateDisplay.getText()+"", hora.getText()+"", lugar.getText()+"" );
				Intent mServiceIntent = new Intent(getBaseContext(), NotificationService.class);
				//Bundle extras =new Bundle();
				model.addEvent(item);
				mServiceIntent.putExtra("nombre",item.getNombre());
				mServiceIntent.putExtra("lugar",item.getLugar());
				mServiceIntent.putExtra("fecha",item.getFecha());
				mServiceIntent.putExtra("descripcion",item.getDescripcion());
				mServiceIntent.putExtra("hora",item.getHora());
				Bitmap bitmap;
		        int img=0;
		       	try{
		       		bitmap = (Bitmap) item.getImagen();
		   		}catch(Exception e){
		   			bitmap= null;
		   			img = (Integer) item.getImagen();
		   		}
		       	if(bitmap==null){
		       		mServiceIntent.putExtra("imagen",img);
		       		mServiceIntent.putExtra("isBitmap", false);
		       	}else{
		       		//extras.putParcelable("bitmap",(Bitmap)bitmap);
		       		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		       		bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
		       		byte[] byteArray = stream.toByteArray();
		       		mServiceIntent.putExtra("bitmap", byteArray);
		       		mServiceIntent.putExtra("isBitmap", true);
		       		//mServiceIntent.putExtra("bitmap",(Bitmap)item.getImagen());
		       	}
		       	//mServiceIntent.putExtras(extras);
				//mServiceIntent.putExtra("Info",10);
				startService(mServiceIntent);
				
				/*Intent upIntent = NavUtils.getParentActivityIntent(getParent());
		        if (NavUtils.shouldUpRecreateTask(getParent(), upIntent)) {
		            // This activity is NOT part of this app's task, so create a new task
		            // when navigating up, with a synthesized back stack.
		            TaskStackBuilder.create(getParent())
		                    // Add all of this activity's parents to the back stack
		                    .addNextIntentWithParentStack(upIntent)
		                    // Navigate up to the closest parent
		                    .startActivities();
		        } else {
		            // This activity is part of this app's task, so simply
		            // navigate up to the logical parent activity.
		            NavUtils.navigateUpTo(getParent(), upIntent);
		        }*/
				//Activity parent=getParent();
				//if(parent!=null){
					//Log.d(null, "*********************PARENT");
					finish();
				//}
			}
		});
	}
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt("mYear", mYear);
		outState.putInt("mMonth", mMonth);
		outState.putInt("mDay", mDay);
		outState.putInt("code", code);
		outState.putString("name", name);
		outState.putParcelable("bitmap", bitmap);
		//outState.putString("bitmapCopy", name);
		//bitmapCopy.pu
		//outState.putBundle("bitmapCopy", bitmapCopy);
		//outState.putByteArray("bitmap", bitmap.);
	}
	
	private void updateDisplay() {
		mDateDisplay.setText(
				new StringBuilder()
				// Month is 0 based so add 1
				.append(mDay).append("-")
				.append(mMonth + 1).append("-")
				.append(mYear).append(" "));
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {   
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this,
					mDateSetListener,
					mYear, mMonth, mDay);  
		}    
		return null;
	}

	/**
	 * Funci�n que se ejecuta cuando concluye el intent en el que se solicita una imagen
	 * ya sea de la c�mara o de la galer�a
	 */
	@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		/**
		 * Se revisa si la imagen viene de la c�mara (TAKE_PICTURE) o de la galer�a (SELECT_PICTURE)
		 */
		if (requestCode == TAKE_PICTURE) {
			/**
			 * Si se reciben datos en el intent tenemos una vista previa (thumbnail)
			 */
			if (data != null) {
				/**
				 * En el caso de una vista previa, obtenemos el extra �data� del intent y 
				 * lo mostramos en el ImageView
				 */
				if (data.hasExtra("data")) { 
					iv = (ImageView)findViewById(R.id.imagen);
					iv.setImageBitmap((Bitmap) data.getParcelableExtra("data"));
				}
				/**
				 * De lo contrario es una imagen completa
				 */    			
			} else {
				/**
				 * A partir del nombre del archivo ya definido lo buscamos y creamos el bitmap
				 * para el ImageView
				 */
				iv = (ImageView)findViewById(R.id.imagen);
				bitmap = BitmapFactory.decodeFile(name);
				iv.setImageBitmap(bitmap);
				/**
				 * Para guardar la imagen en la galer�a, utilizamos una conexi�n a un MediaScanner
				 */
				new MediaScannerConnectionClient() {
					private MediaScannerConnection msc = null; {
						msc = new MediaScannerConnection(getApplicationContext(), this); msc.connect();
					}
					public void onMediaScannerConnected() { 
						msc.scanFile(name, null);
					}
					public void onScanCompleted(String path, Uri uri) { 
						msc.disconnect();
					} 
				};				
			}
			/**
			 * Recibimos el URI de la imagen y construimos un Bitmap a partir de un stream de Bytes
			 */
		} else if (requestCode == SELECT_PICTURE){
			Uri selectedImage = data.getData();
			InputStream is;
			try {
				
				//Log.d(null, "**********************************************GETTING"+name);
				is = getContentResolver().openInputStream(selectedImage);
				BufferedInputStream bis = new BufferedInputStream(is);
				bitmap = BitmapFactory.decodeStream(bis);
				//name = selectedImage.getPath();
				iv = (ImageView)findViewById(R.id.imagen);
				iv.setImageBitmap(bitmap);	
				
			} catch (FileNotFoundException e) {}
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		//if(code==TAKE_PICTURE)
			//iv.setImageBitmap(BitmapFactory.decodeFile(name));
		if(code==SELECT_PICTURE || code==TAKE_PICTURE){
			iv.setImageBitmap(bitmap);
		}
	}
}
